/*
 * The MiniQt Library
 *
 * Copyright (C) 1999 Sandro Sigala <ssigala@globalnet.it>
 */

#ifndef QLIST_H
#define QLIST_H

#include "qminiqt.h"

template <class T>
class QList {
public:
	QList();
	~QList();

	void append(T *item);
	void take(T *item);
	void remove(T *item);
	T *first();
	T *next();
	T *current();

	void setAutoDelete(bool value);
	bool autoDelete();

private:
	bool autodelete;
	struct ListItem { T *item; ListItem *next; };
	ListItem *li_head, *li_current;
};

template <class T>
QList<T>::QList()
{
	autodelete = FALSE;
	li_head = li_current = 0;
}

template <class T>
QList<T>::~QList()
{
	for (ListItem *li = li_head; li != 0; ) {
		ListItem *next = li->next;
		if (autodelete)
			delete li->item;
		li = next;
	}
}

template <class T>
void QList<T>::append(T *item)
{
	ListItem *newli = new ListItem;
	newli->item = item;
	newli->next = 0;

	if (!li_head)
		li_head = newli;
	else {
		ListItem *li;
		for (li = li_head; li->next != 0; li = li->next)
			;
		li->next = newli;
	}
}

template <class T>
void QList<T>::take(T *item)
{
	if (!li_head)
		return;

	// Update the current pointer
	if (li_current && li_current->item == item)
		li_current = li_current->next;

	// Remove the first item
	if (li_head->item == item) {
		ListItem *li = li_head;
		li_head = li_head->next;
		delete li;
		return;
	}

	// Remove an interim item
	for (ListItem *li = li_head; li->next != 0; li = li->next)
		if (li->next->item == item) {
			ListItem *del = li->next;
			li->next = li->next->next;
			delete del;
			return;
		}
}

template <class T>
void QList<T>::remove(T *item)
{
	take(item);
	if (autodelete)
		delete item;
}

template <class T>
T *QList<T>::first()
{
	li_current = li_head;
	return li_head ? li_head->item : 0;
}

template <class T>
T *QList<T>::next()
{
	if (li_current)
		li_current = li_current->next;
	return li_current ? li_current->item : 0;
}

template <class T>
T *QList<T>::current()
{
	return li_current ? li_current->item : 0;
}

template <class T>
void QList<T>::setAutoDelete(bool value)
{
	autodelete = value;
}

template <class T>
bool QList<T>::autoDelete()
{
	return autodelete;
}

#endif // !QLIST_H
